/**
 * 
 */
package qy.jalgotrade.strategy.position;

import java.time.ZonedDateTime;

import com.google.common.math.DoubleMath;

import qy.jalgotrade.broker.Order;
import qy.jalgotrade.broker.OrderEvent;
import qy.jalgotrade.utils.CommonUtils;

/**
 * @author c-geo
 *
 */
public class ClosedState extends PositionState {

	/**
	 * 
	 */
	public ClosedState() {

	}

	/* (non-Javadoc)
	 * @see qy.jalgotrade.strategy.position.PositionState#onEnter(qy.jalgotrade.strategy.position.Position)
	 */
	@Override
	public void onEnter(Position position) {

		// Set the exit datetime if the exit order was filled.
		if (position.exitFilled()) {
			ZonedDateTime exitDateTime = position.getExitOrder().getExecutionInfo().getDateTime();
			position.setExitDateTime(exitDateTime);
		}

		assert DoubleMath.fuzzyEquals(position.getShares(), 0, CommonUtils.FUZZY_EQUAL_TOLERANCE_MATH);
		position.getStrategy().unregisterPosition(position);
	}

	/* (non-Javadoc)
	 * @see qy.jalgotrade.strategy.position.PositionState#canSubmitOrder(qy.jalgotrade.strategy.position.Position, qy.jalgotrade.broker.Order)
	 */
	@Override
	public void canSubmitOrder(Position position, Order order) throws Exception {

		throw new Exception("The position is closed");
	}

	/* (non-Javadoc)
	 * @see qy.jalgotrade.strategy.position.PositionState#onOrderEvent(qy.jalgotrade.strategy.position.Position, qy.jalgotrade.broker.OrderEvent)
	 */
	@Override
	public void onOrderEvent(Position position, OrderEvent orderEvent) throws Exception {

		throw new Exception(String.format("Invalid order event \"%s\" in ClosedState", orderEvent.getEventType()));
	}

	/* (non-Javadoc)
	 * @see qy.jalgotrade.strategy.position.PositionState#isOpen(qy.jalgotrade.strategy.position.Position)
	 */
	@Override
	public boolean isOpen(Position position) {

		return false;
	}

	/* (non-Javadoc)
	 * @see qy.jalgotrade.strategy.position.PositionState#exit(qy.jalgotrade.strategy.position.Position, double, double, boolean)
	 */
	@Override
	public void exit(Position position, double stopPrice, double limitPrice, boolean goodTillCanceled) {

	}
}
